using System;
using System.Linq;
using Honest.MES.Contracts.Attributes;
using Honest.MES.Contracts.Interfaces;
using Honest.MES.WPF.Constants;
using Prism.Container.DryIoc;
using Prism.Ioc;
using Prism.Modularity;
using Prism.Navigation.Regions;

namespace Honest.MES.WPF.Services
{
    public class ModuleInitializationService : IModuleInitializationService
    {
        private readonly IContainerProvider _containerProvider;
        private readonly IRegionManager _regionManager;
        private readonly IModuleDiscoveryService _moduleDiscoveryService;
        private readonly ILoggerService _loggerService;

        public ModuleInitializationService(
            IContainerProvider containerProvider,
            IRegionManager regionManager,
            IModuleDiscoveryService moduleDiscoveryService,
            ILoggerService loggerService)
        {
            _containerProvider = containerProvider;
            _regionManager = regionManager;
            _moduleDiscoveryService = moduleDiscoveryService;
            _loggerService = loggerService;

            _moduleDiscoveryService.ModulesDiscovered += OnModulesDiscovered;
        }

        public void InitializeModules()
        {
            _moduleDiscoveryService.DiscoverModules();
        }

        private void OnModulesDiscovered(object sender, Honest.MES.Contracts.Events.ModulesDiscoveredEventArgs e)
        {
            foreach (var moduleType in e.Modules.OrderBy(GetModuleLoadOrder))
            {
                try
                {
                    InitializeModule(moduleType);
                }
                catch (Exception ex)
                {
                    _loggerService.Error(ex, $"初始化模块 {moduleType.Name} 失败");
                }
            }
        }

        private int GetModuleLoadOrder(Type moduleType)
        {
            var attribute = _moduleDiscoveryService.DiscoverModuleInfo(moduleType);
            return attribute?.LoadOrder ?? 100;
        }

        private void InitializeModule(Type moduleType)
        {
            var attribute = _moduleDiscoveryService.DiscoverModuleInfo(moduleType);

            if (attribute != null && !attribute.IsEnabled)
            {
                _loggerService.Info($"跳过禁用的模块: {attribute.ModelName}");
                return;
            }

            try
            {
                // 优先通过容器创建实例，支持依赖注入
                var module = _containerProvider.Resolve(moduleType) as IModule;
                if (module != null)
                {
                    module.RegisterTypes(_containerProvider as IContainerRegistry);
                    module.OnInitialized(_containerProvider);

                    if (attribute != null && !string.IsNullOrEmpty(attribute.ViewName))
                    {
                        RegisterModuleView(attribute, moduleType);
                    }

                    _loggerService.Info($"已通过容器初始化模块: {moduleType.Name}");
                }
                else
                {
                    _loggerService.Warn($"无法将类型 {moduleType.Name} 解析为IModule");
                }
            }
            catch (Exception ex)
            {
                _loggerService.Error(ex, $"通过容器创建模块实例失败: {moduleType.Name}");
                // 降级方案：如果容器解析失败，尝试使用Activator.CreateInstance
                try
                {
                    if (Activator.CreateInstance(moduleType) is IModule module)
                    {
                        module.RegisterTypes(_containerProvider as IContainerRegistry);
                        module.OnInitialized(_containerProvider);

                        if (attribute != null && !string.IsNullOrEmpty(attribute.ViewName))
                        {
                            RegisterModuleView(attribute, moduleType);
                        }

                        _loggerService.Info($"已通过Activator初始化模块: {moduleType.Name}");
                    }
                }
                catch (Exception innerEx)
                {
                    _loggerService.Error(innerEx, $"通过Activator创建模块实例也失败: {moduleType.Name}");
                }
            }
        }

        private void RegisterModuleView(ModelInfoAttribute attribute, Type moduleType)
        {
            try
            {
                var viewType = moduleType.Assembly.GetType(attribute.ViewName);
                if (viewType != null)
                {
                    _regionManager.RegisterViewWithRegion(RegionNames.MainRegion, viewType);
                    _loggerService.Info($"已注册视图: {attribute.ViewName}");
                }
                else
                {
                    _loggerService.Warn($"找不到视图类型: {attribute.ViewName}");
                }
            }
            catch (Exception ex)
            {
                _loggerService.Error(ex, $"注册视图 {attribute.ViewName} 失败");
            }
        }

        public void Dispose()
        {
            _moduleDiscoveryService.ModulesDiscovered -= OnModulesDiscovered;
        }
    }
}